<html>

<head>
    <title>main</title>
    <link rel="stylesheet"
        href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap-theme.min.css" />

</head>

<style>
    body {
        background: #eee;
        padding: 5% 0;
    }

    video {
        background: black;
        border: 1px solid gray;
    }

    .call-page {
        position: relative;
        display: block;
        margin: 0 auto;
        width: 500px;
        height: 500px;
    }

    #localVideo {
        width: 150px;
        height: 150px;
        position: absolute;
        top: 15px;
        right: 15px;
    }

    #remoteVideo {
        width: 500px;
        height: 500px;
    }
</style>

<body>

    <div id="callPage" class="call-page">
        <video id="localVideo" autoplay></video>
        <video id="remoteVideo" autoplay></video>

        <div class="row text-center">
            <div class="col-md-12">
                <input id="callToUsernameInput" type="text" placeholder="username to call" />
                <button id="callBtn" class="btn-success btn">Call</button>
                <button id="hangUpBtn" class="btn-danger btn">Hang Up</button>
            </div>
        </div>

    </div>

    <script type="text/javascript">
        //our username
        var connectedUser;

        //connecting to our signaling server
        var conn = new WebSocket("ws://localhost:9999/video/xuchenxi");

        conn.onopen = function () {
            console.log("Connected to the signaling server");
        };

        //when we got a message from a signaling server
        conn.onmessage = function (msg) {
            console.log("Got message", msg.data);

            var data = JSON.parse(msg.data);

            switch (data.type) {
                case "login":
                    handleLogin(data.success);
                    break;
                //when somebody wants to call us
                case "offer":
                    handleOffer(data.offer, data.name);
                    break;
                case "answer":
                    handleAnswer(data.answer);
                    break;
                //when a remote peer sends an ice candidate to us
                case "candidate":
                    handleCandidate(data.candidate);
                    break;
                case "leave":
                    handleLeave();
                    break;
                default:
                    break;
            }
        };

        conn.onerror = function (err) {
            console.log("Got error", err);
        };

        //alias for sending JSON encoded messages
        function send(message) {
            //attach the other peer username to our messages
            if (connectedUser) {
                message.name = connectedUser;
            }

            conn.send(JSON.stringify(message));
        }

        //******
        //UI selectors block
        //******


        var callPage = document.querySelector("#callPage");
        var callToUsernameInput = document.querySelector("#callToUsernameInput");
        var callBtn = document.querySelector("#callBtn");

        var hangUpBtn = document.querySelector("#hangUpBtn");

        var localVideo = document.querySelector("#localVideo");
        var remoteVideo = document.querySelector("#remoteVideo");

        var yourConn;
        var stream;

        // callPage.style.display = "none";

        var PeerConnection = (window.webkitRTCPeerConnection || window.mozRTCPeerConnection || window.RTCPeerConnection || undefined);
        var RTCSessionDescription = (window.webkitRTCSessionDescription || window.mozRTCSessionDescription || window.RTCSessionDescription || undefined);

        navigator.getUserMedia = (navigator.getUserMedia ||
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.msGetUserMedia);
        //**********************
        //Starting a peer connection
        //**********************

        //getting local video stream
        navigator.getUserMedia({ video: true, audio: true }, function (myStream) {
            stream = myStream;

            //displaying local video stream on the page
            localVideo.srcObject = stream;

            //using Google public stun server
            var configuration = {
                "iceServers": []
            };

            yourConn = new PeerConnection(configuration);

            // setup stream listening
            yourConn.addStream(stream);

            //when a remote user adds stream to the peer connection, we display it
            yourConn.onaddstream = function (e) {
                remoteVideo.srcObject = e.stream;
            };

            // Setup ice handling
            yourConn.onicecandidate = function (event) {
                if (event.candidate) {
                    send({
                        type: "candidate",
                        candidate: event.candidate
                    });
                }
            };

        }, function (error) {
            console.log(error);
        });


        //initiating a call
        callBtn.addEventListener("click", function () {
            consoloe.log("start call")
            var callToUsername = callToUsernameInput.value;
            
            if (callToUsername.length > 0) {

                connectedUser = callToUsername;

                // create an offer
                yourConn.createOffer(function (offer) {
                    send({
                        type: "offer",
                        offer: offer
                    });

                    yourConn.setLocalDescription(offer);
                }, function (error) {
                    alert("Error when creating an offer");
                });

            }
        });

        //when somebody sends us an offer
        function handleOffer(offer, name) {
            connectedUser = name;
            yourConn.setRemoteDescription(new RTCSessionDescription(offer));

            //create an answer to an offer
            yourConn.createAnswer(function (answer) {
                yourConn.setLocalDescription(answer);

                send({
                    type: "answer",
                    answer: answer
                });

            }, function (error) {
                alert("Error when creating an answer");
            });
        }

        //when we got an answer from a remote user
        function handleAnswer(answer) {
            yourConn.setRemoteDescription(new RTCSessionDescription(answer));
        }

        //when we got an ice candidate from a remote user
        function handleCandidate(candidate) {
            yourConn.addIceCandidate(new RTCIceCandidate(candidate));
        }

        //hang up
        hangUpBtn.addEventListener("click", function () {

            send({
                type: "leave"
            });

            handleLeave();
        });

        function handleLeave() {
            connectedUser = null;
            remoteVideo.src = null;

            yourConn.close();
            yourConn.onicecandidate = null;
            yourConn.onaddstream = null;
        }
    </script>

</body>

</html>